import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import Textarea from '@/components/Textarea';
import { useAppSelector } from '@/store';
import {
  getUserProfile,
  updataPhotoApi,
  updataProfileAction,
} from '@/store/action/user';
import { ProfileType } from '@/store/reducer/user';
import history from '@/utils/history';
import { removeTokenInfo } from '@/utils/storage';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';

export default function ProfileEdit() {
  const { profile } = useAppSelector((state) => state.user);

  // 日期选择器
  const [pickShow, setPickShow] = useState(false);

  // 将文本框修改为受控组件
  const [intro, setIntro] = useState('');

  // 将昵称的input改为受控组件
  const [name, setName] = useState('');

  // 修复input框的默认值
  useEffect(() => {
    setName(profile.name || '');
  }, [profile.name]);

  // 监听文本框
  useEffect(() => {
    setIntro(profile.intro || '');
  }, [profile.intro]);

  // 定义右侧弹出框的显示与隐藏
  const [rightVisible, setRightVisible] = useState(false);

  // 1. 定义复用模态框的类型
  type EditType = 'photo' | 'gender' | 'name' | 'intro';

  // 2. 定义模态框的状态
  const [editType, setEditType] = useState('' as EditType);

  // 弹出框 声明state，设置显示与隐藏
  const [visible, setVisible] = useState(false);

  // 获取 个人资料
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getUserProfile());
  }, [dispatch]);

  //  创建 ref对象
  const upload = useRef<HTMLInputElement>(null);

  //  定义上传图片的点击事件
  const handleUpload = () => {
    upload.current?.click();
  };

  // 4. 给input框添加onchange事件
  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      await dispatch(updataPhotoApi(formData));
      Toast.show({ content: '更新成功' });
      // 关闭弹窗
      setVisible(false);
    }
  };

  //  定义底部弹出框的点击事件
  const handelShowEdit = (editType: EditType) => {
    setEditType(editType);
    setVisible(true);
  };

  //  定义右侧弹出框的点击事件
  const handelRihgtEdit = (editType: EditType) => {
    setEditType(editType);
    setRightVisible(true);
  };

  // 编辑用户个人信息
  const handleUpdateProfile = async (data: Partial<ProfileType>) => {
    await dispatch(updataProfileAction(data));
    Toast.show({ content: '更新成功' });
    setVisible(false);
    setRightVisible(false);
    setPickShow(false);
  };

  // 清空输入完没提交的值
  const handleShowName = () => {
    setRightVisible(false);
    setName(profile.name);
    setIntro(profile.intro);
  };

  // input 回车事件
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      editType === 'name' && handleUpdateProfile({ name });
      editType === 'intro' && handleUpdateProfile({ intro });
    }
  };

  // 编辑登录逻辑
  const handleLogout = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '是否确定退出',
      onConfirm: () => {
        // 清除 本地存储的token
        removeTokenInfo();
        // 返回登录页
        history.push('/login');
        // 提示用户
        Toast.show('退出登录成功');
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handelShowEdit('photo')}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => handelRihgtEdit('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => handelRihgtEdit('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => handelShowEdit('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setPickShow(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          {/*
           2. 将ref绑定给input
            4. 给input框添加onchange事件
          */}
          <input
            ref={upload}
            className="avatar-upload"
            type="file"
            onChange={(e) => handleFileUpload(e)}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </div>
      <DatePicker
        visible={pickShow}
        // 取消按钮
        onCancel={() => setPickShow(false)}
        min={new Date('1990-01-01')}
        max={new Date()}
        // 默认值
        defaultValue={new Date()}
        value={new Date(profile.birthday)}
        // 确定按钮
        onConfirm={(val) => {
          handleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
        }}
      />

      {/* 底部弹出层 */}
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
        onMaskClick={() => setVisible(false)}
      >
        {/*  3. 判断是性别还是头像 */}
        {editType === 'photo' && (
          <>
            <div className="list-item" onClick={handleUpload}>
              拍照
            </div>
            <div className="list-item" onClick={handleUpload}>
              本地选择
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
        {editType === 'gender' && (
          <>
            <div
              className="list-item"
              onClick={() => handleUpdateProfile({ gender: 0 })}
            >
              男
            </div>
            <div
              className="list-item"
              onClick={() => handleUpdateProfile({ gender: 1 })}
            >
              女
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
      </Popup>
      {/* 右侧弹出层 */}
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        // 不可见时卸载内容
        destroyOnClose
      >
        {editType === 'name' && (
          <>
            <NavBar
              onBack={handleShowName}
              right={
                <span
                  className="submit-btn"
                  onClick={() => handleUpdateProfile({ name })}
                >
                  提交
                </span>
              }
            >
              编辑用户信息
            </NavBar>
            <div className="edit-content">
              <h3 className="edit-title">编辑昵称</h3>
              {/* 将输入框改为受控组件 */}
              <Input
                className="edit-input"
                value={name}
                onChange={(e) => setName(e.target.value)}
                autoFocus
                onKeyDown={(e) => handleKeyDown(e)}
              />
            </div>
          </>
        )}
        {editType === 'intro' && (
          <>
            <NavBar
              onBack={handleShowName}
              right={
                <span
                  className="submit-btn"
                  onClick={() => handleUpdateProfile({ intro })}
                >
                  提交
                </span>
              }
            >
              编辑简介信息
            </NavBar>
            <div className="edit-content">
              <h3 className="edit-title">编辑简介</h3>
              <Textarea
                value={intro}
                onChange={(e) => setIntro(e.target.value)}
              />
            </div>
          </>
        )}
      </Popup>
    </div>
  );
}
